<template>
  <div class="company-account">
    <xl-search-form :formItems="formItems" @search="search"></xl-search-form>
    <xl-table :columns="columns" :action="loadData" ref="xlTableRef">
      <template slot="top">
        <el-button type="primary" size="small" style="margin-bottom: 10px" @click="dialogVisible = true">添加公司账号</el-button>
        <upload-excel :title="'批量添加公司账号'" :onSuccess="handleSuccess" />
      </template>
      <template slot="avatar" slot-scope="{ row }">
        <img :src="row.avatar" alt="" />
      </template>
      <template slot="createdAt" slot-scope="{ row }">
        <span>{{ timeFormat(row.createdAt) }}</span>
      </template>
      <template slot="enableStatus" slot-scope="{ row }">
        <span style="color: #67c23a" v-if="row.enableStatus === 1">启用</span>
        <span style="color: #f56c6c" v-else>禁用</span>
      </template>
      <template slot="action" slot-scope="{ row }">
        <el-button type="text" @click="handleEdit(row)">编辑</el-button>
      </template>
    </xl-table>

    <el-dialog :title="title" :visible.sync="dialogVisible" width="30%" @close="resetForm('formRef')">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="50px">
        <el-form-item label="账号" prop="username">
          <el-input v-model="form.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="companyId === ''">
          <el-input v-model="form.password"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="enableStatus">
          <el-radio-group v-model="form.enableStatus">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogVisible = false">取 消</el-button>
        <el-button size="small" type="primary" @click="handleSubmit('formRef')">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import UploadExcel from '@/components/UploadExcel/index.vue'
import { columns, formItems, excelMap } from './const'
import { getAccountList, createAccount, updateAccount, batchCreateAccount } from '@/api/account'
import { parseTime } from '@/utils/index'

export default {
  name: 'CompanyAccount',
  components: { UploadExcel },
  data() {
    return {
      columns,
      formItems,
      title: '新增公司账号',
      dialogVisible: false,
      companyId: '',
      form: {
        username: '',
        password: '',
        role: 'company',
        enableStatus: 1
      },
      rules: {
        username: { required: true, trigger: 'blur', message: '账号不能为空' },
        password: { required: true, trigger: 'blur', message: '密码不能为空' }
      }
    }
  },
  methods: {
    // 批量添加账号
    async handleSuccess({ results, header }) {
      const list = this.excelFormatConvert(results)
      const res = await batchCreateAccount({ list })
      if (res.code === 200) {
        this.$message.success('添加成功')
        this.$refs['xlTableRef'].loadData()
      }
    },
    // 编辑
    handleEdit(row) {
      this.form = { ...row }
      this.dialogVisible = true
      this.title = '更新学生账号'
      this.companyId = row.id
    },
    // 添加学生账号
    handleSubmit(name) {
      this.$refs[name].validate(async (valid) => {
        if (!valid) return false

        let result
        let message
        if (this.companyId !== '') {
          result = await updateAccount(this.form)
          message = '更新成功'
        } else {
          result = await createAccount(this.form)
          message = '添加成功'
        }

        if (result.code === 200) {
          this.$message.success(message)
          this.dialogVisible = false
          this.$refs['xlTableRef'].loadData()
        }
      })
    },
    // 重置
    resetForm(name) {
      if (name) {
        this.$refs[name].resetFields()
      }
      this.dialogVisible = false
      this.title = '新增学生账号'
      this.companyId = ''
    },
    // excel数据转换成后端需要的字段
    excelFormatConvert(data) {
      const result = data.map((item) => {
        const formData = { role: 'company', enableStatus: 1 }
        Object.keys(item).forEach((key) => {
          const enKey = excelMap[key]
          formData[enKey] = item[key] + ''
        })
        return formData
      })
      return result
    },
    // 格式化时间
    timeFormat(value) {
      return parseTime(new Date(value), '{y}-{m}-{d}')
    },
    search(params) {
      this.$refs['xlTableRef'].loadData(params)
    },
    loadData(params) {
      params.role = 'company'
      return getAccountList(params)
    }
  }
}
</script>

<style lang="scss" scoped>
img {
  width: 60px;
  height: 60px;
}
</style>
